package com.qcu.controller.staff;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.qcu.entity.ExaminationInfo;
import com.qcu.service.ExaminationInfoService;
import com.qcu.service.OrderInfoService;
import com.qcu.util.Response;
import com.qcu.util.ResponseCode;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

/**
 * @Name: MyComputer
 * @ClassName ExaminationController
 * @Description:
 * @date 2025/4/9 21:35
 */
@RestController
@RequestMapping("/staff/exam")
public class ExaminationController {
    @Resource
    OrderInfoService orderInfoService;

    @Resource
    private ExaminationInfoService examinationInfoService;

    @GetMapping("/{inhabitantId}")
    public Response getExamInfo(@PathVariable String inhabitantId) {
        ExaminationInfo info = examinationInfoService.getOne(new LambdaQueryWrapper<ExaminationInfo>().eq(ExaminationInfo::getId, inhabitantId).eq(ExaminationInfo::getState, 0));
        if (info == null){
            return orderInfoService.getExamInfo(inhabitantId);
        }
        String content = info.getContent();
        JSONObject jsonObject = JSON.parseObject(content);
        if (jsonObject != null) {
            HashMap<String, String> resultMap = new HashMap<>();
            for (String key : jsonObject.keySet()) {
                resultMap.put(key, jsonObject.getString(key));
            }
            return Response.success(resultMap);
        }
        return Response.failure(ResponseCode.FAILURE);
    }

    @PutMapping("/{inhabitantId}")
    public Response updateExamInfo(@PathVariable String inhabitantId, @RequestBody HashMap<String, String> data) {
        ExaminationInfo examinationInfo = new ExaminationInfo();
        examinationInfo.setId(inhabitantId);
        examinationInfo.setContent(JSON.toJSONString(data));
        if (examinationInfoService.saveOrUpdate(examinationInfo)) {
            return Response.success();
        }
        return Response.failure(ResponseCode.FAILURE);
    }

    @PutMapping("/complete/{inhabitantId}")
    public Response completeExam(@PathVariable String inhabitantId) {
        boolean update = examinationInfoService.update(new LambdaUpdateWrapper<ExaminationInfo>().eq(ExaminationInfo::getId, inhabitantId).set(ExaminationInfo::getState, 1));
        // TODO:邮件发送结果 -----> 已完成
        examinationInfoService.sendResultToUser(inhabitantId);


        return update ? Response.success() : Response.failure(ResponseCode.FAILURE);
    }
}
